import numpy as np
import pandas as pd

# 模拟用户-商品评分矩阵
# 用户数量: 4
# 商品数量: 5
ratings = np.array([
    [5, 3, 0, 1, 2],
    [4, 0, 0, 1, 1],
    [1, 1, 0, 5, 4],
    [1, 0, 0, 4, 0]
])

# 将0评分视为缺失值
ratings_masked = np.ma.masked_where(ratings == 0, ratings)

# 进行SVD分解
U, s, VT = np.linalg.svd(ratings_masked, full_matrices=False)

# 选择前k个奇异值
k = 2
S = np.diag(s[:k])
U_k = U[:, :k]
VT_k = VT[:k, :]

# 重建评分矩阵
ratings_reconstructed = np.dot(U_k, np.dot(S, VT_k))

# 填充缺失值
ratings_predicted = np.ma.filled(ratings_reconstructed, fill_value=0)

# 打印结果
print("原始评分矩阵:\n", ratings)
print("\n重建的评分矩阵:\n", ratings_predicted)

# 推荐商品
user_id = 0  # 选择第一个用户
recommendations = ratings_predicted[user_id]

# 过滤掉已经评分的商品
recommendations[ratings[user_id] > 0] = 0

# 找到推荐得分最高的商品
top_recommendation = np.argmax(recommendations)
print(f"\n推荐给用户 {user_id} 的商品是商品 {top_recommendation + 1}")